package com.cdc.guidepages.viewpager;

import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;

import com.cdc.guidepages.R;

import java.util.ArrayList;
import java.util.List;

public class ViewpagerActivity extends AppCompatActivity implements ContentFragment.OnFragmentInteractionListener {
    private LinearLayout ll_indicator;
    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;
    private List<Fragment> fragments=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewpager);
        initView();

        for(int i=0;i<3;i++){
            ContentFragment contentFragment= ContentFragment.newInstance(i);
            fragments.add(contentFragment);
        }
        pagerAdapter=new GuidePageAdapter(getSupportFragmentManager(),fragments);

        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new OnPageChangeListener(){

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                for(int i=0;i<fragments.size();i++){
                    ll_indicator.getChildAt(i).setBackgroundResource(position==i ? R.drawable.dot_focus : R.drawable.dot_normal);
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initIndicator();
    }

    /**
     * 初始化指示器
     */
    private void initIndicator(){
        int width= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10f,getResources().getDisplayMetrics());
        LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(width,width);
        lp.rightMargin=2*width;
        for(int i=0;i<fragments.size();i++){
            View view=new View(this);
            view.setId(i);
            view.setBackgroundResource(i==0 ? R.drawable.dot_focus : R.drawable.dot_normal);
            view.setLayoutParams(lp);
            ll_indicator.addView(view,i);
        }
    }

    private void initView() {
        viewPager=findViewById(R.id.viewPager);
        ll_indicator=findViewById(R.id.ll_indicator);
    }


    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}
